<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class Vote extends Model
{

    /**
     * 投票接口
     * @param $topId 投票id
     * @param $userId 用户id
     * @param $ip 用户ip地址
     */
    public function vote($topId, $userId, $ip, $sels) {
        $data = [];

        foreach ($sels as $k => $v) {
            $t = [];
            $t['tid'] = $topId;
            $t['uid'] = $userId;
            $t['ip'] = $ip;
            $t['sid'] = $v;
            $t['time'] = date('Y-m-d H:i:s', time());
            $data[] = $t;
        }

        DB::table('votes')->insert($data);
    }

    /**
     *  获取结果接口
     *  $res = $this->getResult($topId);
        dd($res);
     *
     * @param $topId
     * @return mixed
     */
    public function getResult($topId) {
        $res = DB::table('votes')->where('tid', $topId)->get();

        $result = [];
        foreach ($res as $k => $v) {
            $sid = $v->sid;
            if (isset($result[$sid])) {
                $result[$sid]['num']++;
            } else {
                $result[$sid]['num'] = 1;
            }
        }

        $sum = 0;

        foreach ($result as $k => $v) {
            $sum += $v['num'];
        }

        foreach ($result as $k => $v) {
            $result[$k]['percent'] = ceil($v['num'] / $sum * 100);
        }

        $result['total'] = $sum;

        return $result;
    }

    /**
     * 判断是否已经投过票
     */
    public function isVoted($topId, $ip) {
        return count(DB::table('votes')->where(['tid'=>$topId, 'ip'=>$ip])->first()) > 0;
    }
}
